package com.example.demo.controller;

import com.example.demo.mapper.DepartmentMapper;
import com.example.demo.pojo.Department;
import com.example.demo.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/api/department")
public class DepartmentController {
    
    @Autowired
    private DepartmentMapper departmentMapper;
    
    // 查询所有部门
    @GetMapping("/findAll")
    public Result findAll() {
        List<Department> list = departmentMapper.findAll();
        return new Result(200, "查询成功", list);
    }
    
    // 根据ID查询部门
    @GetMapping("/findById")
    public Result findById(int id) {
        Department department = departmentMapper.findById(id);
        return new Result(200, "查询成功", department);
    }
    
    // 新增部门
    @PostMapping("/save")
    public Result saveDepartment(@RequestBody Department department) {
        int result = departmentMapper.saveDepartment(department);
        if (result > 0) {
            return new Result(200, "添加成功", result);
        } else {
            return new Result(400, "添加失败", null);
        }
    }
    
    // 更新部门
    @PostMapping("/update")
    public Result updateDepartment(@RequestBody Department department) {
        int result = departmentMapper.updateDepartment(department);
        if (result > 0) {
            return new Result(200, "更新成功", result);
        } else {
            return new Result(400, "更新失败", null);
        }
    }
    
    // 删除部门
    @GetMapping("/delete")
    public Result deleteDepartment(int id) {
        int result = departmentMapper.deleteDepartment(id);
        if (result > 0) {
            return new Result(200, "删除成功", result);
        } else {
            return new Result(400, "删除失败", null);
        }
    }
}